package cn.pconline.autoclub.service;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.BbsActionLog;
import cn.pconline.autoclub.entity.ClubIntegral;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.DynaImage;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.DynaReply;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.util.dyna.PostReply;
import cn.pconline.autoclub.util.dyna.TopicDyna;
import cn.pconline.r.client.SimpleHttpTemplate;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.gelivable.dao.GeliDao;
import org.gelivable.dao.GeliOrm;
import org.gelivable.dao.SqlBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 同步论坛到车友会（动态、回复）
 *
 * @author zhouruxuan
 * @date 2014年9月2日 上午10:30:17
 */
public class DynaBbsActionLogService {

    private static final Logger log = LoggerFactory.getLogger(DynaBbsActionLogService.class);
    //帖子操作类型代码
    /** 创建主帖 */
    public static final int CREATE_TOPIC_TYPE = 100;
    /** 删除主帖 */
    public static final int DELETE_TOPIC_TYPE = 101;
    /** 设置精华 */
    public static final int SET_PICK_TYPE = 102;
    /** 取消精华 */
    public static final int REMOVE_PICK_TYPE = 103;
    /** 设置推荐 */
    public static final int SET_RECOMMEND_TYPE = 104;
    /** 取消推荐 */
    public static final int REMOVE_RECOMMEND_TYPE = 105;
    /** 回帖 */
    public static final int REPLY_TOPIC_TYPE = 106;
    /** 删除回帖 */
    public static final int REMOVE_REPLY_TOPIC_TYPE = 107;
    /** 车主认证 */
    public static final int SET_USER_VIP_TYPE = 108;
    /** 取消车主认证 */
    public static final int REMOVE_USER_VIP_TYPE = 109;
    /** 修改帖子 */
    public static final int UPDATE_TOPIC_TYPE = 110;
    /** 恢复主帖 */
    public static final int ROCLLBACK_TOPIC_TYPE = 111;
    /** 恢复回帖 */
    public static final int ROCLLBACK_REPLY_TOPIC_TYPE = 112;
    /** 修改回复内容 */
    public static final int UPDATE_REPLY_TYPE = 113;
    
    private static final Map<Integer, Integer> TOPIC_ACTION_INTEGRAL_ID = new HashMap<Integer, Integer>();

    static {
        TOPIC_ACTION_INTEGRAL_ID.put(CREATE_TOPIC_TYPE, PetrolService.ADD_PERSONAL_PETROL_ITEM_TOPIC);
        TOPIC_ACTION_INTEGRAL_ID.put(DELETE_TOPIC_TYPE, PetrolService.ADD_PERSONAL_PETROL_ITEM_TOPIC_DELETE);
        TOPIC_ACTION_INTEGRAL_ID.put(ROCLLBACK_TOPIC_TYPE, PetrolService.ADD_PERSONAL_PETROL_ITEM_TOPIC);

        TOPIC_ACTION_INTEGRAL_ID.put(SET_PICK_TYPE, PetrolService.ADD_PERSONAL_PETROL_ITEM_PICK);
        TOPIC_ACTION_INTEGRAL_ID.put(REMOVE_PICK_TYPE, PetrolService.ADD_PERSONAL_PETROL_ITEM_PICK_CANCEL);

        TOPIC_ACTION_INTEGRAL_ID.put(SET_RECOMMEND_TYPE, PetrolService.ADD_PERSONAL_PETROL_ITEM_RECOMMEND);
        TOPIC_ACTION_INTEGRAL_ID.put(REMOVE_RECOMMEND_TYPE, PetrolService.ADD_PERSONAL_PETROL_ITEM_RECOMMEND_CANCEL);
    }
    @Autowired
    private GeliDao geliDao;
    @Autowired
    private GeliOrm geliOrm;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private SimpleHttpTemplate simpleHttpTemplate;
    @Autowired
    private MemberService memberService;
    @Autowired
    private IntfService intfService;
    @Autowired
    private DynaService dynaService;
    @Autowired
    private UserService userService;
    @Autowired
    private PetrolService petrolService;
    @Autowired
    private DynaIndexService dynaIndexService;

    /**
     * 创建新的帖子
     *
     * @param bbsActionLog
     * @param userId
     * @param clubId
     * @param petrol 由于可能不只是创建动作会调用此方法，所以油值外部自己计算
     */
    public void createTopic(BbsActionLog bbsActionLog, long userId, long clubId, int petrol) {
        TopicDyna topicDyna = parseActionLog2DynaInfo(bbsActionLog, clubId);
        topicDyna.setPetrol(petrol);
        List<DynaImage> dynaImages = parseActionLog2DynaImages(bbsActionLog, userId);
        dynaService.createTopicDyna(topicDyna, dynaImages);
    }

    /**
     * 创建新的帖子
     *
     * @param bbsActionLog
     * @param userId
     * @param clubId
     */
    public void createTopic(BbsActionLog bbsActionLog, long userId, long clubId) {
        //对于非车友会会员的帖子也会同步过来，所以加精操作、设置推荐都需要调用这个方法
        //所以这里设置油值要使用固定的创建动作的ID，不能使用传参进来的actionLog的ID
        TopicDyna topicDyna = parseActionLog2DynaInfo(bbsActionLog, clubId);
        createTopic(bbsActionLog, userId, clubId, calculateDynaPetrol(topicDyna, CREATE_TOPIC_TYPE));
    }

    /**
     * 修改帖子
     *
     * @param bbsActionLog
     * @param userId
     * @param clubId
     */
    public void updateTopic(BbsActionLog bbsActionLog, long userId, long clubId) {
        TopicDyna topicDyna = parseActionLog2DynaInfo(bbsActionLog, clubId);
        List<DynaImage> dynaImages = parseActionLog2DynaImages(bbsActionLog, userId);
        dynaService.updateDynaInfo(topicDyna, dynaImages);
    }

    /**
     * 回复帖子
     *
     * @param bbsActionLog
     */
    public void replyTopic(BbsActionLog bbsActionLog, long clubId) {
        PostReply postReply = parseActionLog2PostReply(bbsActionLog);
        DynaReply reply = dynaService.replyTopicDyna(postReply);
        dynaService.updateLastReplyInfoByTopicId(
                postReply.getTopicId(), clubId, postReply.getTopicCreateAt(),
                postReply.getUserId(), postReply.getCreateName(), postReply.getCreateAt());
		dynaService.setJson4BipBbsTopics(postReply);
    }

    /**
     * actionLog转回复实体,回复帖子同步有效
     *
     * @param bbsActionLog
     * @return
     */
    public PostReply parseActionLog2PostReply(BbsActionLog bbsActionLog) {
        JSONObject jsonObject = JSONObject.parseObject(bbsActionLog.getContent());
        JSONObject jsonQuote = JSONObject.parseObject(jsonObject.getString("quote"));

        PostReply postReply = new PostReply();
        postReply.setCreateAt(jsonObject.getDate("lastPostAt"));
        postReply.setCreateName(jsonObject.getString("userName"));//论坛传的是nickname
        postReply.setFloor(jsonObject.getIntValue("floor"));
        postReply.setIsQuote(jsonObject.getBooleanValue("isQuote"));
        postReply.setMessage(jsonObject.getString("message"));
        postReply.setPostId(jsonObject.getLongValue("postId"));
        postReply.setTopicCreateAt(jsonObject.getDate("topicCreateAt"));
        postReply.setTopicUserId(jsonObject.getLongValue("topicUserId"));
        postReply.setTopicTitle(jsonObject.getString("topicTitle"));

        postReply.setPostToFloor(jsonQuote.getIntValue("floor"));
        postReply.setPostToNickName(jsonQuote.getString("userName"));
        postReply.setPostToPostId(jsonQuote.getLongValue("postId"));
        postReply.setPostToUserId(jsonQuote.getLongValue("userId"));
        postReply.setPostToMessage(jsonQuote.getString("message"));

        postReply.setTopicId(bbsActionLog.getTopicId());
        postReply.setUserId(bbsActionLog.getUserId());
       
        return postReply;

    }

    /**
     * 获取图片列表
     *
     * @param bbsActionLog
     * @param userId
     * @return
     */
    private List<DynaImage> parseActionLog2DynaImages(BbsActionLog bbsActionLog, long userId) {
        JSONObject jsonObject = JSONObject.parseObject(bbsActionLog.getContent());
        String imageString = jsonObject.getString("images");
        if (imageString == null) {
            return null;
        } else {
            JSONArray jsonArray = JSONArray.parseArray(imageString);
            List<DynaImage> list = new ArrayList<DynaImage>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject json = JSONObject.parseObject(jsonArray.getString(i));
                DynaImage dynaImage = new DynaImage();
                dynaImage.setSeq(json.getIntValue("seq"));
                dynaImage.setUrl(json.getString("url"));
                dynaImage.setWidth(json.getIntValue("width"));
                dynaImage.setHeight(json.getIntValue("height"));
                if (StringUtils.isBlank(dynaImage.getUrl())) {
                    continue;
                }
                list.add(dynaImage);
            }
            return list;
        }
    }

    /**
     * actionLog转topic,只有创建帖子的时候有效
     *
     * @param bbsActionLog
     * @param clubId
     * @return
     */
    private TopicDyna parseActionLog2DynaInfo(BbsActionLog bbsActionLog, long clubId) {
        JSONObject jsonObject = JSONObject.parseObject(bbsActionLog.getContent());

        TopicDyna topicDyna = new TopicDyna();
        topicDyna.setTopicId(bbsActionLog.getTopicId());
        topicDyna.setClubId(clubId);
        topicDyna.setForumId(jsonObject.getLongValue("forumId"));
        topicDyna.setUserId(jsonObject.getLongValue("userId"));
        topicDyna.setForumName(StringUtils.defaultString(jsonObject.getString("forumName")));
        topicDyna.setLastPostAt(new Date(jsonObject.getLongValue("lastPostAt")));
        topicDyna.setCreateDate(new Date(jsonObject.getLongValue("topicCreateAt")));
        topicDyna.setLastPostBy(jsonObject.getLongValue("topicUserId"));
        topicDyna.setLastPostName(userService.getNickNameByUserId(jsonObject.getLongValue("topicUserId")));
        topicDyna.setMessage(StringUtils.defaultString(jsonObject.getString("message")));
        topicDyna.setTopicTitle(StringUtils.defaultString(jsonObject.getString("title")));
        topicDyna.setPick(jsonObject.getIntValue("pick"));
        topicDyna.setRecommend(jsonObject.getIntValue("recommend"));
        topicDyna.setPostCount(jsonObject.getIntValue("postCount"));
        topicDyna.setCreateName(jsonObject.getString("userName"));//论坛传的是nickname
        topicDyna.setType(jsonObject.getString("type"));//帖子类型，question为提问帖标记
        
        return topicDyna;
    }

    /**
     * 修改帖子回复内容
     *
     * @param bbsActionLog
     */
    public void updateDynaPost(BbsActionLog bbsActionLog) {
        JSONObject jsonObject = JSONObject.parseObject(bbsActionLog.getContent());
        long topicId = jsonObject.getLongValue("topicId");
        Date createAt = jsonObject.getDate("topicCreateAt");
        long postId = jsonObject.getLongValue("postId");
        String content = jsonObject.getString("message");
        dynaService.updateDynaReply(topicId, createAt, postId, content);
    }

    /**
     * 删除帖子回复内容
     *
     * @param bbsActionLog
     */
    public void deleteDynaPost(BbsActionLog bbsActionLog) {
        JSONObject jsonObject = JSONObject.parseObject(bbsActionLog.getContent());
        long topicId = jsonObject.getLongValue("topicId");
        Date createAt = jsonObject.getDate("topicCreateAt");
        long postId = jsonObject.getLongValue("postId");
        dynaService.deleteDynaReply(topicId, createAt, postId);
    }

    /**
     * 恢复帖子回复内容
     *
     * @param bbsActionLog
     */
    public void rollbackDynaPost(BbsActionLog bbsActionLog) {
        JSONObject jsonObject = JSONObject.parseObject(bbsActionLog.getContent());
        long topicId = jsonObject.getLongValue("topicId");
        Date createAt = jsonObject.getDate("topicCreateAt");
        long postId = jsonObject.getLongValue("postId");
        dynaService.rollbackDynaReply(topicId, createAt, postId);
    }

    /**
     * 设置帖子为精华帖子
     *
     * @param bbsActionLog
     */
    public void setPick(BbsActionLog bbsActionLog, long userId, long clubId) {
        TopicDyna topicDyna = parseActionLog2DynaInfo(bbsActionLog, clubId);
        DynaInfo isExistInfo = dynaService.findDynaInfoByTopicId(topicDyna.getTopicId(), topicDyna.getCreateDate());
        
        if (isExistInfo != null) {//如果帖子存在，就以原来的油值为准
            createTopic(bbsActionLog, userId, clubId, isExistInfo.getPetrol());
        } else {//如果帖子不存在就走正常的流程
            createTopic(bbsActionLog, userId, clubId);
        }
        long topicId = topicDyna.getTopicId();
        Date createAt = topicDyna.getCreateDate();
        dynaService.setPick(topicId, createAt, calculateDynaPetrol(topicDyna, bbsActionLog.getTypeId()));

    }

    /**
     * 取消帖子为精华帖子
     *
     * @param bbsActionLog
     */
    public void removePick(BbsActionLog bbsActionLog) {
        //如果帖子已经存在，修改其状态为精华
        TopicDyna topicDyna = parseActionLog2DynaInfo(bbsActionLog, 0);
        long topicId = topicDyna.getTopicId();
        Date createAt = topicDyna.getCreateDate();
        dynaService.removePick(topicId, createAt, calculateDynaPetrol(topicDyna, bbsActionLog.getTypeId()));
    }

    /**
     * 设置帖子为推荐帖子
     *
     * @param bbsActionLog
     */
    public void setRecommend(BbsActionLog bbsActionLog, long userId, long clubId) {
        TopicDyna topicDyna = parseActionLog2DynaInfo(bbsActionLog, clubId);
        DynaInfo isExistInfo = dynaService.findDynaInfoByTopicId(topicDyna.getTopicId(), topicDyna.getCreateDate());
        if (isExistInfo != null) {//如果帖子存在，就以原来的油值为准
            createTopic(bbsActionLog, userId, clubId, isExistInfo.getPetrol());
        } else {//如果帖子不存在就走正常的流程
            createTopic(bbsActionLog, userId, clubId);
        }
        
        long topicId = topicDyna.getTopicId();
        Date createAt = topicDyna.getCreateDate();
        dynaService.setRecommend(topicId, createAt, calculateDynaPetrol(topicDyna, bbsActionLog.getTypeId()));
    }

    /**
     * 取消帖子为推荐帖子
     *
     * @param bbsActionLog
     */
    public void removeRecommend(BbsActionLog bbsActionLog) {
        TopicDyna topicDyna = parseActionLog2DynaInfo(bbsActionLog, 0);
        long topicId = topicDyna.getTopicId();
        Date createAt = topicDyna.getCreateDate();
        dynaService.removeRecommend(topicId, createAt, calculateDynaPetrol(topicDyna, bbsActionLog.getTypeId()));
    }

    /**
     * 删除帖子
     *
     * @param bbsActionLog
     */
    public void deleteTopic(BbsActionLog bbsActionLog) {
        JSONObject jsonObject = JSONObject.parseObject(bbsActionLog.getContent());
        long topicId = jsonObject.getLongValue("topicId");
        Date createAt = jsonObject.getDate("topicCreateAt");

        DynaInfo dynaInfo = dynaService.findDynaInfoByTopicId(topicId, createAt);
        if (dynaInfo != null) {
            dynaService.deleteClubDyna(dynaInfo.getClubId(), dynaInfo.getDynaInfoId());//修改车友会动态分表
            dynaService.deleteUserDyna(dynaInfo.getCreateBy(), dynaInfo.getDynaInfoId());//修改用户动态分表
            dynaIndexService.deleteDynaIndex( dynaInfo.getDynaInfoId() );	//删除动态索引
        }

    }

    /**
     * 恢复帖子
     *
     * @param bbsActionLog
     */
    public void rollbackTopic(BbsActionLog bbsActionLog) {
        JSONObject jsonObject = JSONObject.parseObject(bbsActionLog.getContent());
        long topicId = jsonObject.getLongValue("topicId");
        Date createAt = jsonObject.getDate("topicCreateAt");

        DynaInfo dynaInfo = dynaService.findDynaInfoByTopicId(topicId, createAt);
        if (dynaInfo != null) {
            dynaService.rollbackClubDyna(dynaInfo.getClubId(), dynaInfo.getDynaInfoId());//修改车友会动态分表
            dynaService.rollbackUserDyna(dynaInfo.getCreateBy(), dynaInfo.getDynaInfoId());//修改用户动态分表
        }

    }

    /**
     * 处理论坛传过来的日志(动态、回复） 
     *
     * @param bbsActionLog
     * @param typeId
     */
    public void service(BbsActionLog bbsActionLog, int typeId) {

        //验证用户
        if (bbsActionLog == null || bbsActionLog.getUserId() <= 0L) {
            return;
        }

        //验证log是否已经存在
        BbsActionLog existLog = find(bbsActionLog.getLogId(), bbsActionLog.getCreateAt().getTime());
        if (existLog != null) {
            //BbsActionLogService那里已经做了反馈
            //changeBbsStatus(bbsActionLog);
            return;
        }

        //判断用户是否登录
        User user = userService.authUser(bbsActionLog.getUserId());
        if (user == null || user.getUid() == 0L) {
            return;
        }
        long userId = user.getUid();

        //获取车友会ID
        ClubMember clubMember = memberService.findClubMemberByUserId(user.getUid());
        long clubId = 0L;
        if (clubMember != null) {
            clubId = clubMember.getClubId();
        } else {//非车友会会员也要进行回帖，修改回帖，删除回帖，恢复回帖的论坛同步
            if (typeId != REPLY_TOPIC_TYPE && typeId != UPDATE_REPLY_TYPE 
            		&& typeId != REMOVE_REPLY_TOPIC_TYPE 
            		&& typeId != ROCLLBACK_REPLY_TOPIC_TYPE) {
                return;
            }
        }
        
        /*
         * 过滤屏蔽版块
         * http://bbs.pcauto.com.cn/forum-15253.html
         * http://bbs.pcauto.com.cn/forum-15252.html
         * http://bbs.pcauto.com.cn/forum-21245.html
         * http://bbs.pcauto.com.cn/forum-19017.html
         * http://bbs.pcauto.com.cn/forum-19375.html
         */
        /*long[] filteForums = {15253, 15252, 21245, 19017, 19375};
        long forumId = bbsActionLog.getForumId();
        //是屏蔽版块并且回帖操作，发完消息返回
        if(ArrayUtils.contains(filteForums, forumId)) {
            if(typeId == REPLY_TOPIC_TYPE) {//回帖
                PostReply postReply = parseActionLog2PostReply(bbsActionLog);
                dynaService.setJson4BipBbsTopics(postReply);
            }
            return;
        }*/
        
        switch (typeId) {
            case CREATE_TOPIC_TYPE:
                //创建主帖
                createTopic(bbsActionLog, userId, clubId);
                break;
            case UPDATE_TOPIC_TYPE:
                //修改帖子
                updateTopic(bbsActionLog, userId, clubId);
                break;
            case REPLY_TOPIC_TYPE:
                //回帖
                //addReplyTopicPetrol(bbsActionLog, userId, clubId);
                //addDynaPostCount(bbsActionLog, clubId);
                replyTopic(bbsActionLog, clubId);
                break;
            case UPDATE_REPLY_TYPE:
                updateDynaPost(bbsActionLog);
                break;
            case REMOVE_REPLY_TOPIC_TYPE:
                //删除回帖
                //delPostPetrol(bbsActionLog, clubList);
                deleteDynaPost(bbsActionLog);
                break;
            case ROCLLBACK_REPLY_TOPIC_TYPE:
                //恢复回帖
                //addReplyTopicPetrol(bbsActionLog, clubList);
                rollbackDynaPost(bbsActionLog);
                break;
            case SET_PICK_TYPE:
                //设置精华
                setPick(bbsActionLog, userId, clubId);
                break;
            case REMOVE_PICK_TYPE:
                //取消精华
                removePick(bbsActionLog);
                break;
            case SET_RECOMMEND_TYPE:
                //设置推荐
                setRecommend(bbsActionLog, userId, clubId);
                break;
            case REMOVE_RECOMMEND_TYPE:
                //取消推荐
                removeRecommend(bbsActionLog);
                break;
            case DELETE_TOPIC_TYPE:
                //删除主帖
                deleteTopic(bbsActionLog);
                break;
            case ROCLLBACK_TOPIC_TYPE:
                //恢复主帖
                rollbackTopic(bbsActionLog);
                break;


            case SET_USER_VIP_TYPE:
                //车主认证
                //setUserVip(bbsActionLog);
                break;
            case REMOVE_USER_VIP_TYPE:
                //取消车主认证
                //removeUserVip(bbsActionLog);
                break;

            default:
                log.error("接收日志时没有相对应的typeId:" + typeId + ","
                        + " logId:" + bbsActionLog.getLogId()
                        + " topicId:" + bbsActionLog.getTopicId()
                        + " forumId:" + bbsActionLog.getForumId()
                        + " userId:" + bbsActionLog.getUserId()
                        + " typeId:" + typeId
                        + " createAt:" + bbsActionLog.getCreateAt().getTime()
                        + " content:" + bbsActionLog.getContent());
                throw new RuntimeException("接收日志时没有相对应的typeId:" + typeId);
        }
        //BbsActionLogService那里已经做了反馈
        //create(bbsActionLog);
        //changeBbsStatus(bbsActionLog);
    }
    
    
    public void reSyncFromActionLog(BbsActionLog bbsActionLog) {
        //验证用户
        if (bbsActionLog == null || bbsActionLog.getUserId() <= 0L) {
            log.warn("bbsActionLog is null.");
            return;
        }
        int typeId = bbsActionLog.getTypeId();
        //判断用户是否登录
        User user = userService.authUser(bbsActionLog.getUserId());
        if (user == null || user.getUid() == 0L) {
            log.warn("user not found: {}", bbsActionLog.getUserId());
            return;
        }
        long userId = user.getUid();

        //获取车友会ID
        ClubMember clubMember = memberService.findClubMemberByUserId(user.getUid());
        long clubId = 0L;
        if (clubMember != null) {
            clubId = clubMember.getClubId();
        } else {//非车友会会员也要进行回帖，修改回帖，删除回帖，恢复回帖的论坛同步
            log.warn("user not join club: {}", userId);
            if (typeId != REPLY_TOPIC_TYPE && typeId != UPDATE_REPLY_TYPE 
                    && typeId != REMOVE_REPLY_TOPIC_TYPE 
                    && typeId != ROCLLBACK_REPLY_TOPIC_TYPE) {
                log.warn("not post action: {}-{}", bbsActionLog.getTopicId(), typeId);
                return;
            }
        }
        
        switch (typeId) {
            case CREATE_TOPIC_TYPE:
                //创建主帖
                createTopic(bbsActionLog, userId, clubId);
                break;
            case UPDATE_TOPIC_TYPE:
                //修改帖子
                updateTopic(bbsActionLog, userId, clubId);
                break;
            case REPLY_TOPIC_TYPE:
                //回帖
                replyTopic(bbsActionLog, clubId);
                break;
            case UPDATE_REPLY_TYPE:
                updateDynaPost(bbsActionLog);
                break;
            case REMOVE_REPLY_TOPIC_TYPE:
                //删除回帖
                deleteDynaPost(bbsActionLog);
                break;
            case ROCLLBACK_REPLY_TOPIC_TYPE:
                //恢复回帖
                rollbackDynaPost(bbsActionLog);
                break;
            case SET_PICK_TYPE:
                //设置精华
                setPick(bbsActionLog, userId, clubId);
                break;
            case REMOVE_PICK_TYPE:
                //取消精华
                removePick(bbsActionLog);
                break;
            case SET_RECOMMEND_TYPE:
                //设置推荐
                setRecommend(bbsActionLog, userId, clubId);
                break;
            case REMOVE_RECOMMEND_TYPE:
                //取消推荐
                removeRecommend(bbsActionLog);
                break;
            case DELETE_TOPIC_TYPE:
                //删除主帖
                deleteTopic(bbsActionLog);
                break;
            case ROCLLBACK_TOPIC_TYPE:
                //恢复主帖
                rollbackTopic(bbsActionLog);
                break;
        }
    }

    /**
     * 根据logId查找Log 暂时忽略createTime参数
     *
     * @param logId
     * @param createTime
     * @return
     */
    public BbsActionLog find(long logId, long createTime) {
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.appendSql("select * from ").appendSql(geliOrm.getTableName(BbsActionLog.class, createTime));
        sqlBuilder.appendSql(" where log_id = ").appendValue(logId);
        return geliDao.findFirst(BbsActionLog.class, sqlBuilder.getSql(), sqlBuilder.getValues());
    }

    public int calculateDynaPetrol(TopicDyna topicDyna, int typeId) {
        ClubIntegral actionIntergral = petrolService.getById(TOPIC_ACTION_INTEGRAL_ID.get(typeId));
        int dynaPetrol = actionIntergral.getPetrol();

        if (typeId == CREATE_TOPIC_TYPE || typeId == ROCLLBACK_TOPIC_TYPE) {
            if (DynaInfo.PICK_YES == topicDyna.getPick()) {
                ClubIntegral pickIntergral = petrolService.getById(TOPIC_ACTION_INTEGRAL_ID.get(SET_PICK_TYPE));
                dynaPetrol += pickIntergral.getPetrol();
            }

            if (DynaInfo.RECOMMEND_YES == topicDyna.getRecommend()) {
                ClubIntegral recommandIntergral = petrolService.getById(TOPIC_ACTION_INTEGRAL_ID.get(SET_RECOMMEND_TYPE));
                dynaPetrol += recommandIntergral.getPetrol();
            }
        } else if (typeId == DELETE_TOPIC_TYPE) {
            if (DynaInfo.PICK_YES == topicDyna.getPick()) {
                ClubIntegral picIntergral = petrolService.getById(TOPIC_ACTION_INTEGRAL_ID.get(REMOVE_PICK_TYPE));
                dynaPetrol += picIntergral.getPetrol();
            }

            if (DynaInfo.RECOMMEND_YES == topicDyna.getRecommend()) {
                ClubIntegral recommandIntergral = petrolService.getById(TOPIC_ACTION_INTEGRAL_ID.get(REMOVE_RECOMMEND_TYPE));
                dynaPetrol += recommandIntergral.getPetrol();
            }
        }
        if(dynaPetrol < 0) {
            dynaPetrol = 0;//防止出现负油值
        }
        return dynaPetrol;
    }
    
    public List<BbsActionLog> getTopicCreatActionLog(Date date, int num) {
        Date endDate = org.apache.commons.lang.time.DateUtils.addDays(date, 1);
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.appendSql("select id from ").appendSql(geliDao.getTableName(BbsActionLog.class, date.getTime()));
        sqlBuilder.appendSql(" a where create_at > ").appendValue(date).appendSql(" and create_at < ").appendValue(endDate);
        sqlBuilder.appendSql(" and type_id = ").appendValue(CREATE_TOPIC_TYPE);
        sqlBuilder.appendSql(" and not exists (select 1 from ").appendSql(geliDao.getTableName(DynaInfo.class, date.getTime()));
        sqlBuilder.appendSql(" b where b.type in ").appendValues(DynaInfo.getTopicType());
        sqlBuilder.appendSql(" and b.create_date > ").appendValue(date).appendSql(" and b.create_date < ").appendValue(endDate);
        sqlBuilder.appendSql(" and a.topic_id = b.topic_id)");
        return geliDao.page(BbsActionLog.class, date.getTime(), sqlBuilder.getSql(), 1, num, sqlBuilder.getValues());
    }
    
    public List<BbsActionLog> getBbsActionLogByTopicId(long topicId, Date date) {
        Date endDate = org.apache.commons.lang.time.DateUtils.addDays(date, 1);
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.appendSql("select id from ").appendSql(geliDao.getTableName(BbsActionLog.class, date.getTime()));
        sqlBuilder.appendSql(" where create_at > ").appendValue(date).appendSql(" and create_at < ").appendValue(endDate);
        sqlBuilder.appendSql(" and topic_id = ").appendValue(topicId);
        return geliDao.list(BbsActionLog.class, date.getTime(), sqlBuilder.getSql(), sqlBuilder.getValues());
    }
//    BbsActionLogService那里已经有做反馈处理了，这个service就不需要再处理了
//    /**
//     * 通知论坛更改log状态,提供参数logId
//     *
//     * @param bbsActionLog
//     */
//    public void changeBbsStatus(BbsActionLog bbsActionLog) {
//        String url = systemConfig.getBbsRoot() + "/plugins/autoclub/receive.do";
//        String result = simpleHttpTemplate.post(url, null,
//                new RequestCallback() {
//                    @Override
//                    public void doWithRequest(HttpUriRequest request) throws IOException {
//                        //request.addHeader("POE", "123");
//                    }
//                },
//                new ResponseExtractor<String>() {
//                    @Override
//                    public String extractData(HttpResponse response) throws IOException {
//                        StatusLine statusLine = response.getStatusLine();
//                        if (statusLine.getStatusCode() == 200) {
//                            return EntityUtils.toString(response.getEntity());
//                        } else {
//                            throw new IOException(statusLine.toString());
//                        }
//                    }
//                },
//                EntityBuilder.entity().param("logId", bbsActionLog.getLogId()).build());
//    }
}
